<script lang="ts" setup>
import {ref} from "vue";
import {getUserUploadDataApi} from "@/api/user";
import {onLoad, onPullDownRefresh} from "@dcloudio/uni-app";
import type {UserAnimalItem} from "@/types/user";
import UploadItem from "@/subPkg/upload/components/uploadItem.vue";
import UploadImage from "@/subPkg/upload/components/uploadImage.vue";
import {getUserUploadImagesApi} from "@/api/upload";
import type {UploadImageDTO} from "@/types/upload";

const {safeAreaInsets,windowWidth} = uni.getSystemInfoSync()

// 判断类型
const title = ref('')
const type = ref<0 | 1 | 2 | 3>(0)
onLoad(async (option) => {
  type.value = Number(option?.type) as 0 | 1 | 2 | 3
  switch (type.value) {
    case  0:
      title.value = '待审核'
      break
    case  1:
      title.value = '审核通过'
      break
    case  2:
      title.value = '失败/取消'
  }
  // 获取数据
  await uni.startPullDownRefresh()
})
const loading = ref(true)
onPullDownRefresh(async () => {
  setTimeout(() => {
    refreshData()
    uni.stopPullDownRefresh()
  }, 500)
})
onLoad(async () => {
  getUserUploadDataList().finally(() => {
    setTimeout(() => {
      loading.value = false
    }, 100)
  })
})

const page = ref(1)
const pageSize = ref(10)
const uploadList = ref<UserAnimalItem[]>([])
// 获取用户上传的数据
const getUserUploadDataList = async () => {
  const res = await getUserUploadDataApi(page.value, pageSize.value, type.value)
  uploadList.value!.length >= 1
      ? uploadList.value?.push(...res.data.data)
      : uploadList.value = res.data.data
  if (page.value * pageSize.value >= res.data.total) {
    isNoMore.value = true
  }
}

// 点击菜单
const filterUploadList = (value: 0 | 1 | 2 | 3) => {
  uni.navigateTo({
    url: '/subPkg/upload/upload-second/upload-second?type=' + value
  })
}
// 加载更多
const isNoMore = ref(false)
const isLoadMore = ref(false)
const onLoadMore = async () => {
  if (isLoadMore.value) {
    return
  }
  if (isNoMore.value) {
    // uni.showToast({title: '没有更多了', icon: 'none', duration: 4000})
    return
  }
  isLoadMore.value = true
  page.value++
  await getUserUploadDataList()
  isLoadMore.value = false
}

// 用户取消上传数据
const onUserCancel = async (id: number) => {
  uploadList.value = []
  await getUserUploadDataList()
}
const onUpdateUserUpload = async () => {
  uploadList.value = []
  await getUserUploadDataList()
}

// 顶部tab切换
const imagePage = ref(1)
const imagePageSize = ref(5)
const imageDataList = ref<UploadImageDTO[]>([])
const imageNoMore = ref(false)
const activeTab = ref(0)
const list = [{
  name: '图文',
}, {
  name: '图集',
}]
type Tab = {
  name: string,
  index: number
}
const onChangeUpload = (data: Tab) => {
  activeTab.value = data.index
  if (data.index === 0) {
    delPopup.value.close()
    cancelPopup.value.close()
  } else if (data.index === 1) {
    if (imageDataList.value.length === 0) {
      uni.startPullDownRefresh()
    }
  }
}
// 动态获取屏幕高度
let height = uni.getSystemInfoSync().windowHeight - 50
// #ifdef H5
height = height - 44
// #endif
const delay = ref(false)
// 获取用户上传的图集列表
const getUserUploadImageData = async () => {
  if (imageNoMore.value || delay.value) {
    return
  }
  delay.value = true
  const res = await getUserUploadImagesApi(imagePage.value, imagePageSize.value, type.value)
  delay.value = false
  imageDataList.value = [...imageDataList.value, ...res.data.data]
  if (res.data.page * res.data.pageSize >= res.data.total) {
    imageNoMore.value = true
  }
}
const navHeight = ref('30px')

/**
 * 触底加载
 */
const onScrollToLowerImg = () => {
  if (imageNoMore.value) {
    return
  }
  imagePage.value++
  getUserUploadImageData()
}

// 删除数据时触发
const delPopup = ref()
const uploadImageRef = ref()
const currentDeleteId= ref(-1)
const cancelPopup = ref()

// 触发事件时
const onImgCancel = () => {
  cancelPopup.value.open()
}
const onConfirmCancel = () => {
  uploadImageRef.value.onConfirmCancel()
}
/**
 *确认删除
 * @param id
 */
const onDelete = (id: number) => {
  currentDeleteId.value = id
  delPopup.value.open()
}

/**
 * 刷新当前分页数据
 */
const refreshData = () => {
  loading.value = true
  if (activeTab.value === 0) {
    page.value = 1
    isNoMore.value = false
    uploadList.value = []
    getUserUploadDataList()
  } else if (activeTab.value === 1) {
    imagePage.value = 1
    imageNoMore.value = false
    imageDataList.value = []
    getUserUploadImageData()
  }
  loading.value = false
}

// 监听滚动
const onScroll = (e: any) => {
  if (e.scrollTop > 100) {
    navHeight.value = '50px'
  } else {
    navHeight.value = '80px'
  }
}

/**弹出层处理**/
const moveHandle = () => {
}
/**
 * 确认删除
 */
const onConfirmDel = (value: string) => {
  uploadImageRef.value.onConfirmDel(value)
  // 删除数据
  imageDataList.value = imageDataList.value.filter(item => item.id !== currentDeleteId.value)
}
</script>

<template>
  <view :scroll-y="true" :style="{paddingBottom:'60px',height:'100vh',paddingTop:safeAreaInsets?.top+50+'px'}">
    <view style="position:fixed;top: 0;left: 0;right: 0;z-index: 999;">
      <aw-nav-second :title="'上传管理—'+title">
        <template v-slot:nav-right>
          <text class="cuIcon-moreandroid flex justify-end align-center text-gray"
                style="flex: 1;font-size: 23px"></text>
        </template>
      </aw-nav-second>
    </view>

    <uv-sticky :custom-nav-height="navHeight" bgColor="#fff">
      <view class="padding-left-sm">
        <uv-tabs :activeStyle="{
			color: '#303133',
			fontWeight: 'bold',
			transform: 'scale(1.08)'
    	}" :inactiveStyle="{
			color: '#606266',
			transform: 'scale(1)'
		}"
                 :lineColor="'#39c5bb'"
                 :list="list"
                 itemStyle="padding-left: 15px; padding-right: 15px; height: 42px;"
                 lineWidth="30"
                 @click="onChangeUpload"></uv-tabs>
      </view>

    </uv-sticky>
    <view style="width: 100%">
      <swiper :current="activeTab" :style="{height:height+'px'}" disable-touch="false">
        <swiper-item>
          <view v-show="loading" style="width: 100%;height: 100%">
            <aw-loader></aw-loader>
          </view>
          <scroll-view v-show="!loading" :scroll-y="true" style="width: 100%;height: 100%;" @scrolltolower="onLoadMore">
            <UploadItem ref="uploadImageRef" :upload-list="uploadList" @cancel="onUserCancel" @re_upload="onUpdateUserUpload"></UploadItem>
          </scroll-view>
        </swiper-item>

        <!--     图集   -->
        <swiper-item>
          <view v-show="loading" style="width: 100%;height: 100%">
            <aw-loader></aw-loader>
          </view>
          <scroll-view v-show="!loading" :scroll-y="true" style="width: 100%;height: 100%;"
                       @scrolltolower="onScrollToLowerImg">
            <upload-image @cancel="onImgCancel" :upload-list="imageDataList" @delete="onDelete"></upload-image>
          </scroll-view>
        </swiper-item>
      </swiper>
    </view>
  </view>
  <!--  img的取消-->
  <uni-popup ref="cancelPopup" style="z-index: 10" type="center" @touchmove.stop.prevent="moveHandle">
    <uni-popup-dialog cancel-text="手滑了" confirm-text="取消上传"
                      content="提示取消后的数据可在“失败/取消”中再次上传(图集类暂不支持)"
                      title="确定取消上传"
                      type="info" @confirm="onConfirmCancel">
    </uni-popup-dialog>
  </uni-popup>
  <!--  img的删除-->
  <uni-popup ref="delPopup" type="center">
    <uni-popup-dialog :placeholder="'请输入：'+'确认删除'" cancel-text="手滑了"
                      confirm-text="删除"
                      content="提示删除后的数据不可找回！！！"
                      mode="input"
                      title="确定删除上传数据"
                      type="error" @confirm="onConfirmDel">
    </uni-popup-dialog>
  </uni-popup>
</template>


<style lang="scss" scoped>
/* #ifdef H5 */
body {
  background-color: #f1f1f1;
}

/* #endif */
.msg-menu {
  width: 100%;
  height: 70px;
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 40rpx 20rpx 10rpx 20rpx;
  border-bottom: #e6e6e6 1px solid;
  background-color: #fff;

  &-item {
    width: 150rpx;
    height: 150rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    gap: 10rpx;
  }
}

</style>
